package com.drd.dt.modular.service.impl;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.service.ForVolumeService;
import com.drd.dt.util.HttpConnectionPoolUtil;
import com.drd.dt.util.ResultUtil;
import com.google.common.collect.Lists;
import jodd.util.StringUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.util.*;

@Service
@Transactional
public class ForVolumeServiceImpl implements ForVolumeService {
    private static Logger LOGGER = LoggerFactory.getLogger(ForVolumeServiceImpl.class);
    private final String secretKey = "QNc7SzRDjJKPekSw6CzJDETtE5KmjWmT"; //签名验证
    private final String agentId = "674"; //专属ID

    private final String ym = "http://tq.jfshou.cn";
    private final String homeUrl = ym + "/seller/app/classify";//请求首页接口地址
    private final String orderUrl = ym + "/seller/app/myOrder";//订单接口地址


    /**
     * 订单接口
     *
     * @param user_id   用户ID
     * @param token_id  token
     */
    public Tip getMyOrder(String user_id) {
        if (StringUtils.isEmpty(user_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }

        //1 组装
        SortedMap<String, String> sortedMap = new TreeMap<String, String>();
        sortedMap.put("machineCode", user_id);
        sortedMap.put("agentId", agentId);
        sortedMap.put("timestamp", System.currentTimeMillis() + "");
        //2 获取sing
        String sign = sign(sortedMap);
        sortedMap.put("sign", sign);
        //3 获取365淘卷首页
        System.out.println(sortedMap.toString());
//        String req = getAndPost("POST", orderUrl, new StringBuffer(sortedMap.toString()));
//

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), getUrl(orderUrl,sortedMap));
    }


    /**
     * 获取365H 5界面
     *
     * @param user_id   用户ID
     * @param productNo 365淘券品牌id，用于单品牌跳转 品牌参数列表请咨询商务）
     */
    public Tip getForVolumeHome(String user_id,String productNo) {
        if (StringUtils.isEmpty(user_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }

        //1 组装
        SortedMap<String, String> sortedMap = new TreeMap<String, String>();
        sortedMap.put("machineCode", user_id);
        sortedMap.put("agentId", agentId);
        if (!StringUtils.isEmpty(productNo)) {
            sortedMap.put("productNo", productNo);
        }
        sortedMap.put("timestamp", System.currentTimeMillis() + "");
        //2 获取sing
        String sign = sign(sortedMap);
        sortedMap.put("sign", sign);
        //3 获取365淘卷首页
        System.out.println(sortedMap.toString());
//        String req = getAndPost("POST", homeUrl, new StringBuffer(sortedMap.toString()));
//        response.setContentType("text/html;charset=UTF-8");
//        //直接将完整的表单html输出到页面
//        try {
//            response.getWriter().write(req);
//
//            response.getWriter().flush();
//            response.getWriter().close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), getUrl(homeUrl,sortedMap));
    }


    /**
     * 生成连接
     */
    private String getUrl(String url,SortedMap<String, String> map) {
        if (!StringUtils.isEmpty(url)) {
            url += "?";
        }
        Set<Map.Entry<String, String>> entries = map.entrySet();
        Iterator<Map.Entry<String, String>> iterable = entries.iterator();
        StringBuffer parm = new StringBuffer();

        while (iterable.hasNext()) {
            Map.Entry entry = (Map.Entry) iterable.next();
            String k = String.valueOf(entry.getKey());
            String v = String.valueOf(entry.getValue());
            if (parm.length() >= 1) {
                parm.append("&");
            }
            parm.append(k + "=" + v);
        }

        return url + parm.toString();
    }

    /**
     * 生成签名
     **/
    private String sign(SortedMap<String, String> sortedMap) {

        Set<Map.Entry<String, String>> entries = sortedMap.entrySet();
        Iterator<Map.Entry<String, String>> iterable = entries.iterator();
        StringBuffer sing = new StringBuffer();

        while (iterable.hasNext()) {
            Map.Entry entry = (Map.Entry) iterable.next();
            String k = String.valueOf(entry.getKey());
            String v = String.valueOf(entry.getValue());
            if (StringUtils.isNotEmpty(v) && entry.getValue() != null && !"sign".equals(k) && !"key".equals(k)) {
                if (sing.length() > 0) {
                    sing.append("&");
                }
                sing.append(k + "=" + v);
            }
        }

        //生成 sign
        sing.append("&secretKey=" + secretKey);
        System.out.println(sing.toString());
        //MD5
        return MD5AndToUpperCase(sing.toString(), "md5");
    }


    /**
     * 通过MD5加密
     *
     * @param algorithmStr
     * @return String
     */
    private String MD5AndToUpperCase(String str, String encryp) {
        if (StringUtils.isEmpty(str)) {
            return "";
        }
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(encryp);//加密
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (Exception e) {

        }
        if (messageDigest != null) {
            byte[] da = messageDigest.digest();
            StringBuilder ret = new StringBuilder(da.length << 1);
            for (int i = 0; i < da.length; i++) {
                ret.append(Character.forDigit((da[i] >> 4) & 0xf, 32));
                ret.append(Character.forDigit(da[i] & 0xf, 32));
            }
            System.out.println(ret.toString());
            return ret.toString().toUpperCase();
        }
        return "";
    }


    /**
     * 特殊处理 GET POST请求
     *
     * @param type 请求方式 GET POST
     * @param url  请求地址
     * @param body POST 数据
     **/
    private String getAndPost(String type, String url, StringBuffer body) {
        String response = "";
        CloseableHttpClient httpClient = HttpConnectionPoolUtil.getHttpClient();
        CloseableHttpResponse httpResponse = null;
        HttpEntity entity = null;
        /********GET 对象*********/
        URIBuilder builder = null;
        HttpGet get = null;
        /********GET 对象*********/

        /********POST 对象*********/

        /********POST 对象*********/
        try {
            switch (type) {
                case "GET": {
                    builder = new URIBuilder(url);  // 发送请求
                    get = new HttpGet(builder.build());
                    get.setConfig(RequestConfig.custom() //设置请求头(以及 超时时间)
                            .setConnectTimeout(5000)
                            .setSocketTimeout(5000).build());
                    get.setHeader("Application", "x-www-form-urlencode");
                    httpResponse = httpClient.execute(get);
                    entity = httpResponse.getEntity();
                }
                break;
                case "POST": {
                    HttpPost post = new HttpPost(url);  // 发送请求
                    StringEntity se = new StringEntity(body.toString(), "UTF-8");//设置编码
                    post.setEntity(se);
                    post.setConfig(RequestConfig.custom() //设置请求头(以及 超时时间)
                            .setConnectTimeout(5000)
                            .setSocketTimeout(5000).build());
                    post.setHeader("Application", "x-www-form-urlencode");
                    httpResponse = httpClient.execute(post);
                    entity = httpResponse.getEntity();
                }
                break;
            }

            if (null != entity) {
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    response = EntityUtils.toString(entity, "UTF-8");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    EntityUtils.consume(httpResponse.getEntity());
                    httpResponse.close();
                } catch (IOException e) {
                    LOGGER.error("关闭response失败", e);
                }
            }
        }
        return response;
    }
}
